﻿using log4net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetTaste;
using PhysicalExamination5.Interface;
using PhysicalExamination5.Model;
using PhysicalExamination5.WebApi.Utility.JWT;
using System.IdentityModel.Tokens.Jwt;

namespace PhysicalExamination5.WebApi.Controllers
{
    /// <summary>
    /// 首页相关
    /// </summary>
    [ApiController]
    [ApiVersion("1.0")]
    [Route("[controller]/v{version:apiVersion}")]
    public class IndexController : Controller
    {
        private readonly IIndex _IIndex;
        private readonly ICustomJWTService _ICustomJWTService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private static readonly ILog log = LogManager.GetLogger(typeof(IndexController));

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="IIndex"></param>
        /// <param name="ICustomJWTService"></param>
        /// <param name="httpContextAccessor"></param>
        public IndexController(IIndex IIndex, ICustomJWTService ICustomJWTService, IHttpContextAccessor httpContextAccessor)
        {
            _IIndex = IIndex;
            _ICustomJWTService = ICustomJWTService;
            _httpContextAccessor = httpContextAccessor;

            //配置日志ip地址参数信息
            string ipAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            log4net.GlobalContext.Properties["localIpAddress"] = ipAddress;
        }
        /// <summary>
        /// 根据登录系统、用户Id、角色Id去查询菜单权限
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Route("[action]")]
        public IActionResult Initialize()
        {
            log.Debug($@"API:{System.Reflection.MethodBase.GetCurrentMethod().Name}");
            var accesToken = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.ReadJwtToken(accesToken);
            var DengLuXiTong = token.Claims.FirstOrDefault(t => t.Type == "DengLuXiTong")?.Value;
            var JueSeId = token.Claims.FirstOrDefault(t => t.Type == "JueSeId")?.Value;
            var userId = token.Claims.FirstOrDefault(t => t.Type == "UserId")?.Value;
            return Ok(_IIndex.Initialize(DengLuXiTong,JueSeId,userId));
        }
    }
}
